//
//  FFMainViewController.m
//  ForceField
//
//  Created by Roxanne Brittain on 11/15/11.
//  Copyright (c) 2011 Digifit. All rights reserved.
//

#import "FFMainViewController.h"
#import "FFAppDelegate.h"
#import "FFObjectSettingsViewController.h"

@implementation FFMainViewController

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    world = new FFWorld();
    
    objectArray = [[NSMutableArray alloc] init];
    self.view.backgroundColor = [UIColor darkGrayColor];
    
    UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIBarButtonItem *testerButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewTester)];
    
    UIBarButtonItem *clearButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(onClearButton)];
    
    UIBarButtonItem *playButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(onPlayButton)];
    
    UIBarButtonItem *pauseButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:self action:@selector(onPauseButton)];
    
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.toolbarHidden = NO;
    self.navigationController.toolbar.barStyle = UIBarStyleBlackTranslucent;
    self.toolbarItems = [NSArray arrayWithObjects:testerButton, spacer, playButton,spacer,  pauseButton, spacer, clearButton, nil];
    
    CGRect bounds = [[self view] bounds];
    bounds.size.height-=20;
    world->worldBounds = bounds;
    
	// Do any additional setup after loading the view, typically from a nib.
    
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didRotate:)
                                                 name:@"UIDeviceOrientationDidChangeNotification" object:nil];
    
    
}

-(BOOL)objectShouldTap
{
    return !world->playing;
}

-(void)objectTapped:(FFObjectWrapper*)obj
{
    FFObjectSettingsViewController *vc = [[FFObjectSettingsViewController alloc] initWithObject:obj.object];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)onPlayButton
{
     world->playing = true;
}

-(void)onPauseButton
{
     world->playing = false;
}

-(void)onClearButton
{
    for (FFObjectWrapper *objectWrapper in objectArray) {
        [objectWrapper clear];
    }
    world->clearObjects();
    [objectArray removeAllObjects];
}

- (void) didRotate:(NSNotification *)notification{  
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    world->setDeviceOrientation(orientation);
} 

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self startTimerWithFramerate:.01];
}

-(void)startTimerWithFramerate:(float)fr
{
    lastUpdate = [NSDate date];
    onFrameTimer = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:fr target:self selector:@selector(updateAllObjects) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:onFrameTimer forMode:NSDefaultRunLoopMode];
    NSLog(@"starting timer");
}

-(void)stopTimer
{
    [onFrameTimer invalidate];
    NSLog(@"stopping timer");
}

-(void)addNewTester
{
    FFObjectWrapper *wrapper = world->addNewObject();
    do {
        wrapper.object->randomizeValues(world->worldBounds.size.width, world->worldBounds.size.height);
    } while (world->objectOverlaps(wrapper.object));
    wrapper.objectDelegate = self;
    [self.view insertSubview:wrapper.view atIndex:0];
    [objectArray addObject:wrapper];
}

-(void)updateAllObjects
{
    float s = -1*[lastUpdate timeIntervalSinceNow];
    
    world->refreshWithSeconds(s);
    
    lastUpdate = [NSDate date];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
}

- (void)willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation duration:(NSTimeInterval)duration
{
    world->worldBounds = self.view.bounds;
}

#pragma mark - Flipside View Controller

//- (void)flipsideViewControllerDidFinish:(FFFlipsideViewController *)controller
//{
//    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
//        [self dismissModalViewControllerAnimated:YES];
//    } else {
//        [self.flipsidePopoverController dismissPopoverAnimated:YES];
//    }
//}

- (IBAction)showInfo:(id)sender
{
    [self stopTimer];
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
//        FFFlipsideViewController *controller = [[FFFlipsideViewController alloc] initWithNibName:@"FFFlipsideViewController" bundle:nil];
//        controller.delegate = self;
//        controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
//        [self presentModalViewController:controller animated:YES];
    } else {
//        if (!self.flipsidePopoverController) {
//            FFFlipsideViewController *controller = [[FFFlipsideViewController alloc] initWithNibName:@"FFFlipsideViewController" bundle:nil];
//            controller.delegate = self;
//            
//            self.flipsidePopoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
//        }
//        if ([self.flipsidePopoverController isPopoverVisible]) {
//            [self.flipsidePopoverController dismissPopoverAnimated:YES];
//        } else {
//            [self.flipsidePopoverController presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
//        }
    }
}

@end
